<?php

namespace support\Backend;

use support\Exception\ApiException;
use think\Validate;

/**
 * logic 基类
 */
class BackendLogic
{
    /**
     * server类
     * @var BackendService
     */
    protected BackendService $service;

    /**
     * validate类
     * @var Validate
     */
    protected Validate $validate;


    /**
     * 获取列表
     * @return array
     */
    public function getList(): array
    {

        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (!empty($param['username'])) {
            $where[] = ["username", 'like', "%{$param['username']}%"];
        }
        $list = $this->service->getListPage($where);
        return message($list);
    }

    /**
     * 编辑新增数据
     * @return array
     */
    public function edit()
    {
        //获取数据
        $data = request()->post();
        if (!$data) {
            $data = func_get_args();
        }
        $validate = null;
        //校验数据
        if (!empty($this->validate)) {
            $validate_class = get_class($this->validate);
            $validate = new  $validate_class;
        } else {  //自动验证
            $controller = request()->controller;
            $validate_path = str_replace('controller', 'validate', $controller);
            $validate_class = str_replace('Controller', 'Validate', $validate_path);
            if (class_exists($validate_class)) $validate = new  $validate_class;
        }
        if ($validate instanceof Validate) {
            if (!$validate->check($data)) throw new ApiException($validate->getError());
        }
        //编辑数据
        $this->service->edit($data);
        return message();
    }

    /**
     * 获取详情
     * @return array
     */
    public function info(): array
    {
        $id = request()->input('id', 0);
        if (!$id) throw new ApiException('记录不存在！');
        $info = $this->service->getInfo($id);
        if (!$info) throw new ApiException('记录不存在！');
        return message($info);
    }


    /**
     * 删除
     * @return array
     */
    public function delete(): array
    {
        $ids = request()->post('id');
        if (!$ids) throw new ApiException('记录ID不能为空');
        if (!is_array($ids)) $ids = [$ids];
        $this->service->delete($ids);
        return message([], 20000, '删除成功');
    }

    /**
     * 状态
     * @return array
     */
    public function status(): array
    {
        $id = request()->post('id');
        $status = request()->post('status');
        if (!$id) throw new ApiException('记录ID不能为空');
        if (!in_array($status, [1, 2])) throw new ApiException('状态错误');
        $this->service->save(['status' => $status], $id);
        return message();
    }
}